package com.leon.androidcoursedesign.utils.dataBaseUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.leon.androidcoursedesign.beans.UserAccount;

public class AccountInfoUtils extends SQLiteHelper {
    private final SQLiteHelper sqLiteHelper;
    private final SQLiteDatabase sqLiteDatabase;
    private final String dbName = Tables.AccountInfo.value;

    public AccountInfoUtils(Context context) {
        super(context, 1);

        this.sqLiteHelper = new SQLiteHelper(context, 1);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
    }

    /**
     * 根据ID查询用户是否存在
     *
     * @param id    用户ID
     * @return  返回存在状态
     */
    public boolean queryUser(String id) {
        Cursor cursor = sqLiteDatabase.query(dbName, null, "uid = ?", new String[]{id}, null, null, null);

        int count = cursor.getCount();

        cursor.close();
        return count > 0;
    }

    /**
     * 根据ID查询用户是否存在
     *
     * @param id    用户ID
     * @return  返回存在状态
     */
    public boolean queryUser(String id, String pwd) {
        Cursor cursor = sqLiteDatabase.query(dbName, null, "uid = ? AND pwd = ?", new String[]{id, pwd}, null, null, null);

        int count = cursor.getCount();

        cursor.close();
        return count > 0;
    }

    /**
     * 将用户数据插入‘AccountInfo’中
     *
     * @param userAccount   UserAccount对象
     * @return  返回插入状态
     */
    public boolean addAccountInfo(UserAccount userAccount) {
        ContentValues values = new ContentValues();
        values.put("uid", userAccount.uid);
        values.put("pwd", userAccount.pwd);
        values.put("phone", userAccount.phone);

        long insert = sqLiteDatabase.insert(dbName, null, values);

        return insert > 0;
    }

    /**
     * 关闭数据库连接
     */
    @Override
    public void close() {
        if (sqLiteHelper != null) {
            sqLiteDatabase.close();
            sqLiteHelper.close();
        }
    }
}
